# -*- coding: utf-8 -*-

import os
import logging
import traceback

from flask import Blueprint, request, send_file, send_from_directory, make_response

import config

logger = logging.getLogger(config.flask_app_log)

bp = Blueprint(name="file", import_name=__name__, url_prefix="/file")


@bp.route('/get')
def get():
    relative_path = request.args.get('relative_path', default=None)
    logger.debug("relative_path = %s" % relative_path)
    try:
        file_name = os.path.split(relative_path)[-1]
        directory = os.path.join(config.download_root, os.path.split(relative_path)[0])
        response = make_response(send_from_directory(directory, file_name, as_attachment=True))

        response.headers['Content-Type'] = r'application/octet-stream'
        response.headers['Content-Disposition'] = r'attachment;filename={}'.format(file_name.encode().decode('gbk'))
        return response
    except Exception as e:
        # logger.error(traceback.format_exc(e))
        logger.exception(e)
        return None
    pass


@bp.route('/download/<file_path>/<file_name>')
def download(file_path, file_name):
    logger.debug("relative_path = %s" % os.path.join(file_path, file_name))
    try:
        directory = os.path.join(config.download_root, file_path)
        response = make_response(send_from_directory(directory, file_name, as_attachment=True))
        return response
    except Exception as e:
        logger.error(traceback.format_exc(e))
        return None
    pass
